package co.baiku.boot.youzan;

import co.baiku.boot.AjavaerCache;
import co.baiku.boot.common.tools.JsonTools;
import co.baiku.boot.common.tools.StringTools;
import co.baiku.boot.common.validate.Validation;
import co.baiku.boot.config.YouzanCloudConfig;
import co.baiku.boot.config.YouzanConfig;
import com.youzan.cloud.open.sdk.common.exception.SDKException;
import com.youzan.cloud.open.sdk.core.client.auth.Token;
import com.youzan.cloud.open.sdk.core.client.core.DefaultYZClient;
import com.youzan.cloud.open.sdk.core.client.core.YouZanClient;
import com.youzan.cloud.open.sdk.core.oauth.model.OAuthToken;
import com.youzan.cloud.open.sdk.core.oauth.token.TokenParameter;
import com.youzan.cloud.open.sdk.gen.v1_0_0.api.YouzanItemSkuList;
import com.youzan.cloud.open.sdk.gen.v1_0_0.model.YouzanItemSkuListParams;
import com.youzan.cloud.open.sdk.gen.v1_0_0.model.YouzanItemSkuListResult;
import com.youzan.cloud.open.sdk.gen.v3_0_0.api.YouzanItemSearch;
import com.youzan.cloud.open.sdk.gen.v3_0_0.api.YouzanItemSkuGet;
import com.youzan.cloud.open.sdk.gen.v3_0_0.api.YouzanMultistoreOfflineGet;
import com.youzan.cloud.open.sdk.gen.v3_0_0.api.YouzanMultistoreOfflineSearch;
import com.youzan.cloud.open.sdk.gen.v3_0_0.model.*;
import com.youzan.cloud.open.sdk.gen.v4_0_1.api.YouzanTradesSoldGet;
import com.youzan.cloud.open.sdk.gen.v4_0_1.model.YouzanTradesSoldGetParams;
import com.youzan.cloud.open.sdk.gen.v4_0_1.model.YouzanTradesSoldGetResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
@ConditionalOnProperty("ajavaer.youzan.kdt-id")
public class Youzan {
    private Logger log = LoggerFactory.getLogger(Youzan.class);
    @Resource
    private YouzanConfig youzanConfig;
    @Resource
    private YouzanCloudConfig youzanCloudConfig;
    private YouZanClient yzClient;

    public Youzan() {
        yzClient = new DefaultYZClient();
    }

    /**
     * 获得token
     *
     * @return
     * @see <a href='https://doc.youzanyun.com/doc#/content/35701/36467'>官方文档</a>
     */
    public OAuthToken oauthToken() {
        String tokenKey = youzanCloudConfig.getTokenCacheKey();
        String tokenEntity = AjavaerCache.redis().get(tokenKey);
        if (StringTools.isNotBlank(tokenEntity)) {
            return JsonTools.jsonToBean(tokenEntity, OAuthToken.class);
        } else {
            try {
                DefaultYZClient yzClient = new DefaultYZClient();
                TokenParameter tokenParameter = TokenParameter.self()
                        .clientId(youzanCloudConfig.getClientId())
                        .clientSecret(youzanCloudConfig.getClientSecret())
                        .grantId(youzanConfig.getKdtId()).build();
                OAuthToken codeToken = yzClient.getOAuthToken(tokenParameter);
                //转成成秒钟
                long time = (codeToken.getExpires() - System.currentTimeMillis()) / 1000 - 100;
                AjavaerCache.redis().put(tokenKey, JsonTools.beanToJson(codeToken), time, TimeUnit.SECONDS);
                return codeToken;
            } catch (Exception e) {
                log.error("[Youzan - oauthToken] Exception:" + e.getMessage(), e);
            }
        }
        throw Validation.error("Youzan Token获取失败");
    }

    public Token token() {
        return new Token(oauthToken().getAccessToken());
    }

    /**
     * 有赞商品获取
     *
     * @param params
     * @return
     * @throws SDKException
     * @see <a href='https://doc.youzanyun.com/doc#/content/API/1-299/detail/api/0/20'>官网</a>
     */
    public YouzanItemSearchResult itemSearch(YouzanItemSearchParams params) throws SDKException {
        YouzanItemSearch youzanItemSearch = new YouzanItemSearch();
        youzanItemSearch.setAPIParams(params);
        return yzClient.invoke(youzanItemSearch, token(), YouzanItemSearchResult.class);
    }

    /**
     * 根据商品批量获取其SKU 列表
     *
     * @param params
     * @return
     * @throws SDKException
     * @see <a href='https://doc.youzanyun.com/doc#/content/API/1-299/detail/api/0/741'>官网</a>
     */
    public YouzanItemSkuListResult itemSkuList(YouzanItemSkuListParams params) throws SDKException {
        YouzanItemSkuList youzanItemSkuList = new YouzanItemSkuList();
        youzanItemSkuList.setAPIParams(params);
        return yzClient.invoke(youzanItemSkuList, token(), YouzanItemSkuListResult.class);
    }

    /**
     * 通过商品或者skuId查询规格明细
     *
     * @param youzanItemSkuGetParams
     * @return
     * @throws SDKException
     * @see <a href>https://doc.youzanyun.com/doc#/content/API/1-299/detail/api/0/52</a>
     */
    public YouzanItemSkuGetResult youzanItemSkuGet(YouzanItemSkuGetParams youzanItemSkuGetParams) throws SDKException {
        YouzanItemSkuGet youzanItemSkuGet = new YouzanItemSkuGet();
        youzanItemSkuGet.setAPIParams(youzanItemSkuGetParams);
        return yzClient.invoke(youzanItemSkuGet, token(), YouzanItemSkuGetResult.class);
    }

    /**
     * 交易订单获取
     *
     * @param params
     * @return
     * @throws SDKException
     * @see <a href='https://doc.youzanyun.com/doc#/content/API/1-305/detail/api/0/638'>官网</a>
     */
    public YouzanTradesSoldGetResult tradesSoldGet(YouzanTradesSoldGetParams params) throws SDKException {
        YouzanTradesSoldGet youzanTradesSoldGet = new YouzanTradesSoldGet();
        youzanTradesSoldGet.setAPIParams(params);
        return yzClient.invoke(youzanTradesSoldGet, token(), YouzanTradesSoldGetResult.class);
    }

    /**
     * 网点列表获取
     *
     * @param params
     * @return
     * @throws SDKException
     * @see <a href='https://doc.youzanyun.com/doc#/content/API/1-356/detail/api/0/183'>官网</a>
     */
    public YouzanMultistoreOfflineSearchResult multistoreOfflineSearch(YouzanMultistoreOfflineSearchParams params) throws SDKException {
        YouzanMultistoreOfflineSearch youzanMultistoreOfflineSearch = new YouzanMultistoreOfflineSearch();
        youzanMultistoreOfflineSearch.setAPIParams(params);
        return yzClient.invoke(youzanMultistoreOfflineSearch, token(), YouzanMultistoreOfflineSearchResult.class);
    }

    /**
     * 获取单个网点
     *
     * @param youzanMultistoreOfflineGetParams
     * @return
     * @throws SDKException
     * @see <a href='https://doc.youzanyun.com/doc#/content/API/1-356/detail/api/0/184'>官网</a>
     */
    public YouzanMultistoreOfflineGetResult multistoreOfflineGet(YouzanMultistoreOfflineGetParams youzanMultistoreOfflineGetParams) throws SDKException {
        YouzanMultistoreOfflineGet youzanMultistoreOfflineGet = new YouzanMultistoreOfflineGet();
        youzanMultistoreOfflineGet.setAPIParams(youzanMultistoreOfflineGetParams);
        return yzClient.invoke(youzanMultistoreOfflineGet, token(), YouzanMultistoreOfflineGetResult.class);
    }


}
